import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "benxi_bxsbxxrmzf2"

    province: str = "辽宁省"  # 取表格
    city: str = "本溪市"  # 取表格
    county: str = "本溪县"  # 取表格
    park: str = "None"  # 取表格
    source: str = "本溪市本溪县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.bx.gov.cn/publicity/xzfxx/lzyj/szfwj1"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = "http://www.bx.gov.cn/publicity/xzfxx/lzyj/szfwj1"
        # 设置请求头
        yield scrapy.Request(url=url, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        links = response.xpath("//td[@class='title']/a/@href").getall()  # 取链接
        print("links", len(links), links)
        for link in links:
            if 'http' not in link:
                link = f'http://www.bx.gov.cn{link}'
            yield scrapy.Request(link, callback=self.parse_detail)

        # 翻页逻辑
        if response.meta.get("is_next") is not False:
            # 正则表达式模式，匹配数字
            pattern = r"共(\d+)页</span>"  # 匹配形如 1/10 页 的模式，其中(\d+)用于捕获数字10

            # 使用re.search()函数搜索匹配项
            pages = int(re.search(pattern, response.text).group(1))
            print("总页数：", pages)
            for page in range(2, pages+1):
                print("当前页：", page)
                url = f"http://www.bx.gov.cn/publicity/xzfxx/lzyj/szfwj1_{page}"
                yield scrapy.Request(url=url, callback=self.detail_requests, meta={'is_next': False})

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item()
        if '.pdf' in response.url or '.do' in response.url:
            content = response.url
        else:
            content = response.xpath(".").get()
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['source_url'] = response.url
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = content
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl benxi_bxsbxxrmzf2".split())
